<?php

namespace app\controller\admin;

use app\base\BaseEncryptController;
use app\model\agency\AgencyModel;
use app\model\goods\GoodsCommonModel;
use app\model\order\OrderItemModel;
use app\model\order\OrderModel;
use app\model\user\UserModel;
use think\Request;


/**
 * 工作台
 * Class Dashboard
 * @package app\controller
 */
class Dashboard extends BaseEncryptController
{
    /**
     * 统计
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getStatistics(Request $request)
    {
        $shop_time = $request->param('shop_time');

        if (!empty($shop_time)) {
            $start_time = strtotime($shop_time[0] . " 00:00:00");
            $end_time = strtotime($shop_time[1] . " 23:59:59");
        } else {
            $start_time = strtotime(date("Y-m-") . "1 00:00:00");
            $end_time = strtotime(date("Y-m-d") . " 23:59:59");
        }
        //用户
        $db_user = new UserModel();
        $total_user = $db_user->whereBetween('create_time', $start_time . "," . $end_time)->count();
        // //门店
        $db_agent = new AgencyModel();
        $total_agent = $db_agent->whereBetween('create_time', $start_time . "," . $end_time)->count();

        // //订单
        $db_order = new OrderModel();
        $total_order = $db_order->count();
        $total_order_complete = $db_order->whereIn('order_status', '2,3,4,5')->whereBetween('create_time', $start_time . "," . $end_time)->count();//完成订单
        $order_itme_model = new OrderItemModel();
        $order_itme = $order_itme_model->whereIn('order_status', '2,3,4,5')->whereBetween('create_time', $start_time . "," . $end_time)->select();
        $total_fee = "0.00";
        $totle_profit = "0.00";
        foreach ($order_itme as $key => $value) {
            $total_fee += $value['goods_price'] * $value['goods_number'];//销售额
            $totle_profit += ($value['goods_price'] - $value['cost_price']) * $value['goods_number']; # 盈利
        }
        $total_order_pay = $db_order->where('order_status', '=', 1)->count();//待付款
        $total_order_delivery = $db_order->where('order_status', 3)->count();//已发货
        $total_order_refund = $db_order->getOutCount();//申请退款

        // 交易数据趋势
        $order_time = $request->param('order_time');
        if ($order_time != '') {
            $begin = $order_time[0] . " 00:00:00";
            $end = $order_time[1] . " 23:59:59";
        } else {
            $begin = date('Y-m-d', strtotime('-7 day')) . " 00:00:00";
            $end = date('Y-m-d') . " 23:59:59";
        }
        $trade_order = $db_order->getDataByBetweenDt($begin, $end);
//        $trade_order_arr = [];
//        foreach ($trade_order as $value) {
//            $day_index = date("Ymd", strtotime($value['create_date']));
//            $day = date("Y-m-d", strtotime($value['create_date']));
//            if (isset($trade_order_arr[$day])) {
//                $trade_order_arr[$day_index]['order_total'] += floatval($value['order_total']);
//            } else {
//                $trade_order_arr[$day_index] = [
//                    'create_date' => $day,
//                    'order_total' => floatval($value['order_total'])
//                ];
//            }
//        }
//        $trade_order = [];
//        foreach ($trade_order_arr as $value) {
//            $value['order_total'] = floatval($value['order_total']);
//            $trade_order[] = $value;
//        }
        return self::returnMsg(1, [
            'shop' => [
                'total_user' => $total_user,
                'total_agent' => $total_agent,
                'total_order' => $total_order_complete,
                'total_fee' => round($total_fee, 2),
                'totle_profit' => round($totle_profit, 2),
            ],
            'order' => [
                'total_all' => $total_order,
                'total_pay' => $total_order_pay,
                'total_delivery' => $total_order_delivery,
                'total_refund' => $total_order_refund,
            ],
            'trade_order' => $trade_order
        ]);
    }


    /**
     * 获取订单统计列表
     * @param string $start_time
     * @param string $end_time
     * @return \think\response\Json
     */
    public function getOrder($start_time = '', $end_time = '')
    {
        if (empty($start_time) || empty($end_time)) {
            $start_time = date('Y-m-d', time());
            $end_time = date('Y-m-d', time());
        }
        $db_order = new OrderModel();
        $total_order = $db_order->whereBetweenTime('create_time', $start_time, $end_time)->count();
        $await_order = $db_order->whereBetweenTime('create_time', $start_time, $end_time)->where('order_status', 1)->count();
        $send_order = $db_order->whereBetweenTime('create_time', $start_time, $end_time)->where('order_status', 3)->count();
        $after_order = $db_order->whereBetweenTime('create_time', $start_time, $end_time)->where('out_type', '>', 0)->count();
        return self::returnMsg(1, [
            'total_order' => $total_order,
            'await_order' => $await_order,
            'send_order' => $send_order,
            'after_order' => $after_order,
        ]);
    }

    /**
     * 代理商
     * @param $start_time
     * @param $end_time
     * @return \think\response\Json
     */
    public function getAgencyRank($start_time = '', $end_time = '')
    {
        if (empty($start_time) || empty($end_time)) {
            $start_time = date('Y-m-d', time());
            $end_time = date('Y-m-d', time());
        }
        $order_model = new OrderItemModel();
        $agency_list = $order_model
            ->alias('a')
            ->leftJoin('t_agency b', 'a.agency_id = b.id')
            ->whereBetweenTime('a.create_time', $start_time, $end_time)
            ->field('sum(a.agency_money) as all_agency_money,b.id,b.agency_title')
            ->group('a.agency_id')
            ->where('a.order_status', '>', 2)
            ->where('a.agency_id', '>', 0)
            ->limit(5)->select();
        return self::returnMsg(1, $agency_list);
    }

    /**
     * 商品库存警告
     * @param int $num
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getStoreWarn($num = 10)
    {
        $goods_model = new GoodsCommonModel();
        $goods_list = $goods_model->alias('a')
            ->leftJoin('t_goods g', 'a.goods_id=g.id')
            ->where('g.goods_status', 1)
            ->where('a.goods_sell_price', '>', 0)
            ->where('a.goods_storage', '<', $num)
            ->field('a.goods_storage,a.goods_id,a.goods_title,a.attribute_names,a.attribute_ids')
            ->group('a.attribute_ids')
            ->order('a.goods_storage ASC')
            ->limit(30)
            ->select();
        return self::returnMsg(1, $goods_list);
    }
}
